import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, Dropdown, Popconfirm, message, Divider, Form, Select, Input} from "antd";
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';


const FormItem = Form.Item;
const { Option } = Select;


const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ path, loading }) => ({
  resdata: path.resdata,
  loading: path.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }

  componentWillUnmount(){
    const { dispatch } = this.props;
    dispatch({
      type: `path/fetch_appenddata_clear`,
    })
  }

  componentDidMount () {
    const { pageSize } = this.state;
    const { pagesquery,dispatch } = this.props;
    // 清除path-list数据

    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }

  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if (nextProps.isReloadList === true && this.props.isReloadList === false) {
      const { pageSize, formValues, currentPage } = this.state;
      if(nextProps.detailId===0){
        this.getDataList({},pageSize,1);
      }else{
        this.getDataList(formValues,pageSize,currentPage);
      }
      this.props.sotpReloadList();
    }
  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch } = this.props;
    dispatch({
      type: 'path/fetch_path_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      lineCode:undefined,
      lineName:undefined,
      maintenanceId:undefined
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.lineId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 批量删除
  handleActionList = (type,id) => {
    const { dispatch } = this.props;
    const { selectedRows,formValues, pageSize, currentPage } = this.state;
    if(!id && !selectedRows) return;
    const lineIds= id ? [id] : selectedRows;

    switch (type) {
      case '1':
        dispatch({
          type: 'path/action_path_del',
          payload: {
            lineIds
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("所选路线已删除")
        }).then(()=>{
          this.getDataList(formValues,pageSize,currentPage);
        });
        break;
      // case '2':
      //   dispatch({
      //     type: 'path/action_path_export',
      //     payload: {
      //       attaId,
      //       actionType:4
      //     },
      //   }).then(()=>{
      //     this.setState({
      //       selectedRows: [],
      //     });
      //   }).then(()=>{
      //     message.success("路线导出成功")
      //   });
      //   break;

      default:

        break;
    }
  };


  // 新增model传导-------------------
  handleAddModel = (e) =>{
    this.props.addModelCallBack(e);
  }
  // 详情model传导
  handleDetailModel= (detailInfoId) =>{
    const { dispatch } = this.props;
    const { formValues, currentPage} = this.state;
    router.push({ pathname:`/maintain/route/${detailInfoId}/info`,  query: { ...formValues, currentPage} });
  }

  // 路线养护点
  handlePathCuring = (detailInfoId) =>{
    const { dispatch } = this.props;
    const { formValues, currentPage} = this.state;
    router.push({ pathname:`/maintain/route/${detailInfoId}/curing`,  query: { ...formValues, currentPage} });
  }


  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource, pagesquery } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="路线编号">
              {getFieldDecorator('lineCode',{
                initialValue: pagesquery && pagesquery.lineCode ? pagesquery.lineCode : undefined,
              })(<Input placeholder="请输入路线编号" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="路线名称">
              {getFieldDecorator('lineName',{
                initialValue: pagesquery && pagesquery.lineName ? pagesquery.lineName : undefined,
              })(<Input placeholder="请输入路线名称" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <FormItem label="维保单位">
              {getFieldDecorator('maintenanceId',{
                initialValue: pagesquery && pagesquery.maintenanceId ? pagesquery.maintenanceId : undefined,
              })(
                <Select allowClear={true} placeholder="请选择维保单位"   style={{ width: '100%' }}>
                  {selectSource.maintenance && selectSource.maintenance.map(item => (
                    <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading } = this.props;
    const { selectedRows } = this.state;


    const columns = [
      {
        title: '路线编号',
        dataIndex: 'lineCode',
      },
      {
        title: '路线名称',
        dataIndex: 'lineName',
      },
      {
        title: '维保单位',
        dataIndex: 'maintenanceName',
      },
      {
        title: '联系人',
        dataIndex: 'linkman',
      },
      {
        title: '联系电话',
        dataIndex: 'phone',
      },
      {
        title: '备注',
        dataIndex: 'remarks',
      },
      {
        title: '编制人',
        dataIndex: 'creatorName',
      },
      {
        title: '操作',
        width: 250,
        fixed:'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10103'} >
              <a onClick={() => this.handlePathCuring(row.lineId)}>路线养护点</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10104'} >
              <a onClick={() => this.handleDetailModel(row.lineId)}>详情</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10105'} >
              <a onClick={() => this.handleAddModel(row.lineId)}>修改</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10106'} >
              <Popconfirm title="是否确定要删除?" onConfirm={() => this.handleActionList("1",row.lineId)}  okText="是" cancelText="否">
                <a >删除</a>
              </Popconfirm>
            </Authorized>
          </Fragment>
        ),
      },
    ];




    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
          <div className={styles.tableListOperator}>
            <Authorized authority={'10102'} >
              <Button icon="plus" type="primary"  onClick={() => this.handleAddModel(0)}>
                新增路线
              </Button>
            </Authorized>

            <Authorized authority={'10107'} >
              <Popconfirm title="是否确定要批量删除?" onConfirm={() => this.handleActionList("1")}  okText="是" cancelText="否">
                <Button icon="minus" type="default" disabled={selectedRows.length > 0 ? false : true}>
                  批量删除
                </Button>
              </Popconfirm>
            </Authorized>
            {/*
               <Button type="default" onClick={() => this.handleActionList("2")}>
                导出
              </Button>
            */}

          </div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="lineId"
            scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
